package nio.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer implements Runnable{
    private final Selector selector;
    private boolean stop = false;

    public NIOServer(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        System.out.println("server start succeeded");
        while (!stop) {
            try {
                // 会阻塞到接收到新的状态变化或者配置的超时时间过期
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key;

                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    handle(key);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 处理SelectionKey方法
    private void handle(SelectionKey key) throws IOException {
        if (!key.isValid()) return;

        // ServerSocketChannel特有的有新连接到来状态
        if (key.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            // 获取新连接通道
            SocketChannel sc = ssc.accept();
            // 设置非阻塞状态
            sc.configureBlocking(false);
            sc.socket().setReuseAddress(true);
            // 向多路复用器中注册通道可读状态
            sc.register(selector, SelectionKey.OP_READ);
        }

        if (key.isReadable()) {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = socketChannel.read(readBuffer);
            if (readBytes > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String str = new String(bytes);
                stringBuilder.append(str);
                System.out.println(stringBuilder);

                String backMsg = "Hello I`m NIOServer";
                ByteBuffer writeBuffer = ByteBuffer.allocate(backMsg.length());
                writeBuffer.put(backMsg.getBytes());
                writeBuffer.flip();
                socketChannel.write(writeBuffer);
            } else if (readBytes == -1) {
                key.cancel();
                socketChannel.close();
            }
        }
    }
}
